# -*- coding: utf-8 -*-
from openpyxl import load_workbook
import datetime

class Xlsx(object):
    """Excel文件操作类
    """
    def __init__(self, filepathname):
        self._xlsx_file = filepathname  # 文件名
        self.worksheets = []    # 工作表
        self.rows = []          # 每行数据
        self.monthdays = []     # 按月记录日期
        self.weeks = []         # 周

        self.parse_xlsx(filepathname)

    def parse_xlsx(self, filepathname):
        """解析Excel文件
        """
        wb = load_workbook(filename = filepathname)
        self.worksheets = wb.worksheets
        self.rows = []
        monthdays = {}
        for sheet in self.worksheets:
            if sheet.title == u'勿删':
                continue
            fields = self.__class__.get_fields(sheet)
            if not fields:
                continue
            rows = sheet.rows
            date = None
            for row in rows:
                row_dict = {}
                if self.__class__.row_is_empty(row):
                    continue
                row_index = row[0].value
                if not isinstance(row_index, int):
                    continue
                _date = row[1].value
                date = _date if _date else date
                # 按月份记录所有的日期
                month = datetime.datetime(date.year, date.month, 1)
                monthdays[month] = monthdays.get(month, set())
                monthdays[month].add(date)
                for i in range(len(fields)):
                    r_v = row[i].value
                    row_dict[fields[i]] = r_v
                row_dict.update({
                    'sheet': sheet.title,
                    'date': date,
                })
                self.rows.append(row_dict)
        self.monthdays = []
        self.weeks = []
        months = monthdays.keys()
        months.sort()
        last_sunday = datetime.datetime(1900, 1, 7)
        for month in months:
            day_list = list(monthdays[month])
            day_list.sort()
            self.monthdays.append(day_list)
            for day in day_list:
                weekday = day.weekday()
                if day > last_sunday:
                    if weekday == 6:
                        week = (day - datetime.timedelta(days = 6), day)
                        last_sunday = day
                    else:
                        last_sunday = day + datetime.timedelta(days = 6 - weekday)
                        week = (day, last_sunday)
                    self.weeks.append(week)
        self.monthdays.sort(key = lambda x: x[0])

    @classmethod
    def get_fields(cls, sheet):
        """获取字段名
        """
        rows = sheet.rows
        if len(rows) < 2:
            return None
        fields = []
        parent_field_str = ''
        for i in range(len(rows[1])):
            cell_value = rows[1][i].value
            if cell_value is None:
                cell_value = parent_field_str
            parent_field_str = cell_value
            sub_cell_value = rows[2][i].value
            if sub_cell_value:
                cell_value = "%s - %s" % (cell_value, sub_cell_value)
            cell_value = cell_value.replace('\n', '')
            fields.append(cell_value.encode('utf-8'))
        return fields

    @classmethod
    def row_is_empty(cls, row):
        """判断一行是否为空
        """
        ignore_list = [0]
        for i in range(len(row)):
            if i in ignore_list: continue
            if row[i].value:
                return False
        return True



